package com.jcz.daoImpl;

import java.util.List;

import javax.persistence.JoinColumn;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.jcz.dao.HibernateUtil;
import com.jcz.dao.Vote_ItemDao;
import com.jcz.entity.Vote_Item;

public class Vote_ItemDaoImpl implements Vote_ItemDao {

	/*查找所有item*/
	@Override
	public List<Vote_Item> findAllItem() {
		Session session=null;
		List<Vote_Item> list=null;
		
		try {
			session=HibernateUtil.currentSession();
			Criteria criteria=session.createCriteria(Vote_Item.class);
			list=criteria.list();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/*获取subject投票人数*/
	@Override
	public long findCount(Integer id) {
		Session session=null;
		long itenCount=0;
		
		try {
			session=HibernateUtil.currentSession();
			Criteria criteria=session.createCriteria(Vote_Item.class);
			/*itenCount=(long)criteria.setProjection(Projections.rowCount())*/
			itenCount=(long)criteria.add(Restrictions.eq("subject.vs_id", id))
			.setProjection(Projections.count("vi_id"))
			.uniqueResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return itenCount;
	}

	/*添加记录*/
	@Override
	public boolean addItem(Vote_Item item) {
		Session session=null;
		Transaction tx=null;
		
		try {
			session=HibernateUtil.currentSession();
			tx=session.beginTransaction();
			
			session.save(item);
			
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			tx.rollback();
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/*获取选项的投票人数*/
	@Override
	public long findById(Integer id) {
		Session session=null;
		long itenCount=0;
		
		try {
			session=HibernateUtil.currentSession();
			Criteria criteria=session.createCriteria(Vote_Item.class);
			/*itenCount=(long)criteria.setProjection(Projections.rowCount())*/
			itenCount=(long)criteria.add(Restrictions.eq("options.vo_id", id))
			.setProjection(Projections.count("vi_id"))
			.uniqueResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return itenCount;
	}

}
